import base64 from "base64-js";
import base64url from "base64url";

export default class Base64 {
  static Options = {
    encoding: {
      type: "radio",
      options: [
        { label: "Base64MIME", value: "mime" },
        { label: "Base64URL", value: "url" },
      ],
    },
  };

  options = {
    encoding: "mime",
  };

  static Encoder = class Encoder extends Base64 {
    static Name = "Base64 <%= UIText.encode %>";

    compute(data) {
      switch (this.options.encoding) {
        case "mime":
          return base64.fromByteArray(data);
        case "url":
          return base64url(data);
      }
    }
  };

  static Decoder = class Decoder extends Base64 {
    static Name = "Base64 <%= UIText.decode %>";

    compute(text) {
      switch (this.options.encoding) {
        case "mime":
          let data = base64.toByteArray(text.replace(/[\r\n]/g, ""));
          return Buffer.from(data);
        case "url":
          return base64url.toBuffer(text);
      }
    }
  };
}
